package validators;

import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import rullekake.beans.UsersController;
import rullekake.beans.util.JsfUtil;
import rullekake.beans.util.LocaleHelper;
import rullekake.entities.Users;

/**
 * Sjekker at innholdet i validert felt stemmer med det som allerede er registrert på brukeren som er logget inn.
 *
 */

@FacesValidator("passwordMatchesOldPassword")
public class PasswordCheckPassword implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

        final String password = value.toString();

        final String passwordEncrypted = JsfUtil.encryptsha256(password);

        final UsersController usersController = (UsersController) context.getApplication().evaluateExpressionGet(context, "#{usersController}", UsersController.class);

        final Users user = usersController.getSelected();

        final boolean matchesConfirmation = user.getPassword().equals(passwordEncrypted);

        if (!matchesConfirmation) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    ResourceBundle.getBundle(LocaleHelper.getBundleName()).getString("error_wrongPassword"),
                    ResourceBundle.getBundle(LocaleHelper.getBundleName()).getString("error_wrongPassword")));
        }
    }

}
